#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
User: lyj
DateTime: 2012-05-20 14:21:00

"""

__author__ = 'lyj'



from demos.rabbitmq.settings import amqp_host, amqp_port
import pika
import sys
import time

from pika.adapters import BlockingConnection

pika.log.setup(color=True)


def handle_delivery(channel, method_frame, header_frame, body):
    """Callback"""
    print " [x] Received %r" % (body,)

    # Receive the data in 3 frames from RabbitMQ
    pika.log.info("Basic.Deliver %s delivery-tag %i: %s",
        header_frame.content_type,
        method_frame.delivery_tag,
        body)
    channel.basic_ack(delivery_tag=method_frame.delivery_tag)

    time.sleep(10)
    print " [x] End"

if __name__ == '__main__':
    print ' [*] Waiting for messages. To exit press CTRL+C'

    # Connect to RabbitMQ
    #host = (len(sys.argv) > 1) and sys.argv[1] or '127.0.0.1'
    parameters = pika.ConnectionParameters(host=amqp_host, port=amqp_port)
    connection = BlockingConnection(parameters)

    # Open the channel
    channel = connection.channel()

    # Declare the queue
    channel.queue_declare(queue="test", durable=True,
        exclusive=False, auto_delete=False)

    # We're stuck looping here since this is a blocking adapter
    channel.basic_consume(handle_delivery, queue='test')

    #channel.start_consuming()